<template>
  <div class="menu-manage">
    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAddMenu">+ 新增</el-button>
      <el-button @click="handleExpandCollapse">展开/收起</el-button>
      <el-input v-model="searchKeyword" placeholder="请输入菜单名称" style="width:200px" @keyup.enter="handleSearch" />
      <el-button @click="handleSearch">查询</el-button>
      <div class="toolbar-icons">
        <el-button icon="Refresh" circle size="small" />
        <el-button icon="Grid" circle size="small" />
        <el-button icon="Odometer" circle size="small" />
        <el-button icon="Setting" circle size="small" />
      </div>
    </div>

    <!-- 菜单树形表格 -->
    <el-table
      :data="menuList"
      row-key="id"
      border
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" label="菜单名称" width="180" />
      <el-table-column prop="type" label="类型" width="100" />
      <el-table-column prop="icon" label="图标" width="100">
        <template #default="scope">
          <i :class="scope.row.icon"></i>
        </template>
      </el-table-column>
      <el-table-column prop="path" label="页面地址" />
      <el-table-column prop="permission" label="权限标识" />
      <el-table-column prop="sort" label="排序" width="80" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-switch v-model="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="handleAddMenu(scope.row)">新增</el-button>
          <el-button link type="primary" @click="handleEditMenu(scope.row)">编辑</el-button>
          <el-button link type="danger" @click="handleDeleteMenu(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 菜单编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增菜单' : '编辑菜单'"
      width="400px"
    >
      <el-form :model="menuForm" label-width="100px">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="路由地址" prop="path">
          <el-input v-model="menuForm.path" placeholder="请输入路由地址" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="menuForm.sort" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="menuForm.status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitMenu">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

/**
 * 此页面对应权限管理下的 菜单管理
 */

// 菜单列表数据
const menuList = ref([
  {
    id: 1,
    name: '数据总览',
    type: '菜单',
    icon: 'el-icon-menu',
    path: '/home',
    permission: '/home',
    sort: 0,
    updateTime: '2025-05-13 19:09:00',
    status: true
  },
  {
    id: 2,
    name: '开单',
    type: '菜单',
    icon: 'el-icon-menu',
    path: '',
    permission: '',
    sort: 0,
    updateTime: '2025-05-13 19:09:00',
    status: true
  },
  {
    id: 3,
    name: '订单管理',
    type: '菜单',
    icon: 'el-icon-menu',
    path: '',
    permission: '',
    sort: 0,
    updateTime: '2025-05-13 19:09:00',
    status: true,
    children: [
      {
        id: 31,
        name: '运单管理',
        type: '菜单',
        icon: 'el-icon-menu',
        path: '',
        permission: '',
        sort: 0,
        updateTime: '2025-05-13 19:09:00',
        status: true
      }
    ]
  },
  {
    id: 4,
    name: '客户管理',
    type: '菜单',
    icon: 'el-icon-menu',
    path: '',
    permission: '',
    sort: 0,
    updateTime: '2025-05-13 19:09:00',
    status: true
  },
  {
    id: 5,
    name: '承运管理',
    type: '菜单',
    icon: 'el-icon-menu',
    path: '',
    permission: '',
    sort: 0,
    updateTime: '2025-05-13 19:09:00',
    status: true,
    children: []
  },
  {
    id: 6,
    name: '企业管理',
    type: '菜单',
    icon: 'el-icon-menu',
    path: '',
    permission: '',
    sort: 0,
    updateTime: '2025-05-13 19:09:00',
    status: true
  }
])

// 菜单选项（用于上级菜单选择）
const menuOptions = ref([
  {
    id: 0,
    name: '主目录',
    children: menuList.value
  }
])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')

// 表单相关
const menuForm = reactive({
  id: 0,
  parentId: 0,
  name: '',
  path: '',
  sort: 0,
  status: true
})

const rules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入路由地址', trigger: 'blur' }
  ]
}

// 查詢關鍵字
const searchKeyword = ref('')
// 保存原始菜單數據
const originMenuList = ref(JSON.parse(JSON.stringify(menuList.value)))

const getNowTime = () => {
  const now = new Date()
  const pad = (n: number) => n.toString().padStart(2, '0')
  return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`
}

// 处理菜单操作
const handleAddMenu = (row) => {
  dialogType.value = 'add'
  menuForm.id = Date.now()
  menuForm.parentId = row && row.id ? row.id : 0
  menuForm.name = ''
  menuForm.path = ''
  menuForm.sort = 0
  menuForm.status = true
  dialogVisible.value = true
}

const handleEditMenu = (row) => {
  dialogType.value = 'edit'
  menuForm.id = row.id
  menuForm.name = row.name
  menuForm.path = row.path
  menuForm.sort = row.sort
  menuForm.status = row.status
  dialogVisible.value = true
}

const handleDeleteMenu = (row) => {
  ElMessageBox.confirm(
    `确认删除菜单"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const deleteMenu = (list) => {
      const idx = list.findIndex(item => item.id === row.id)
      if (idx !== -1) {
        list.splice(idx, 1)
        return true
      }
      for (const item of list) {
        if (item.children && deleteMenu(item.children)) return true
      }
      return false
    }
    deleteMenu(menuList.value)
    originMenuList.value = JSON.parse(JSON.stringify(menuList.value))
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const handleSubmitMenu = () => {
  if (!menuForm.name) {
    ElMessage.warning('请输入菜单名称')
    return
  }
  if (dialogType.value === 'add') {
    const newMenu = {
      id: menuForm.id,
      name: menuForm.name,
      type: '菜单',
      icon: '',
      path: menuForm.path,
      permission: menuForm.path,
      sort: menuForm.sort,
      updateTime: getNowTime(),
      status: menuForm.status,
      children: []
    }
    if (menuForm.parentId && menuForm.parentId !== 0) {
      // 新增到對應父節點
      const addToParent = (list) => {
        for (const item of list) {
          if (item.id === menuForm.parentId) {
            if (!item.children) item.children = []
            item.children.push(newMenu)
            return true
          }
          if (item.children && addToParent(item.children)) return true
        }
        return false
      }
      addToParent(menuList.value)
    } else {
      // 新增到根節點
      menuList.value.push(newMenu)
    }
    originMenuList.value = JSON.parse(JSON.stringify(menuList.value))
    ElMessage.success('新增成功')
  } else {
    // 編輯
    const updateMenu = (list) => {
      for (const item of list) {
        if (item.id === menuForm.id) {
          Object.assign(item, {
            name: menuForm.name,
            path: menuForm.path,
            sort: menuForm.sort,
            status: menuForm.status,
            updateTime: getNowTime()
          })
          return true
        }
        if (item.children && updateMenu(item.children)) return true
      }
      return false
    }
    updateMenu(menuList.value)
    originMenuList.value = JSON.parse(JSON.stringify(menuList.value))
    ElMessage.success('修改成功')
  }
  dialogVisible.value = false
}

const handleExpandCollapse = () => {
  // 实现展开/收起逻辑
}

const handleSearch = () => {
  if (!searchKeyword.value) {
    menuList.value = JSON.parse(JSON.stringify(originMenuList.value))
    return
  }
  // 遞迴過濾
  const filterTree = (list) => {
    return list
      .map(item => {
        const children = item.children ? filterTree(item.children) : []
        if (item.name.includes(searchKeyword.value) || children.length) {
          return { ...item, children }
        }
        return null
      })
      .filter(Boolean)
  }
  menuList.value = filterTree(originMenuList.value)
}
</script>

<style scoped>
.menu-manage {
  padding: 20px;
  background-color: #fff;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.toolbar-icons {
  margin-left: auto;
  display: flex;
  gap: 8px;
}

.el-table {
  margin-bottom: 16px;
}

:deep(.el-button--primary) {
  --el-button-bg-color: #4066FF;
  --el-button-border-color: #4066FF;
  --el-button-hover-bg-color: #5C7CFF;
  --el-button-hover-border-color: #5C7CFF;
}

:deep(.el-switch.is-checked .el-switch__core) {
  background-color: #4066FF;
  border-color: #4066FF;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 